package com.dimples.dd.system.controller;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.dimples.dd.common.constant.DDServerConstant;
import com.dimples.dd.common.pojo.PageResult;
import com.dimples.dd.common.result.CommonResult;
import com.dimples.dd.log.core.annotation.ApiLog;
import com.dimples.dd.log.core.enums.OperateTypeEnum;
import com.dimples.dd.system.model.form.MenuForm;
import com.dimples.dd.system.model.query.MenuPageQuery;
import com.dimples.dd.system.model.vo.MenuTreeVO;
import com.dimples.dd.system.model.vo.RouteVO;
import com.dimples.dd.system.service.SystemMenuService;
import com.dimples.dd.web.core.annotation.PreventDuplicateResubmit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单控制器
 *
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/6/30
 */
@Tag(name = "03.菜单接口")
@RestController
@Validated
@RequestMapping("/menus")
@RequiredArgsConstructor
@Slf4j
public class SysMenuController {

    @Resource
    private SystemMenuService systemMenuService;

    @Operation(summary = "路由列表")
    @GetMapping("/routes")
    @PreAuthorize("@ss.hasPerm('system:menu:query')")
    @ApiLog(operateType = OperateTypeEnum.SELECT, applicationName = DDServerConstant.DD_SERVER_SYSTEM, enable = false)
    public CommonResult<RouteVO> listRoutes() {
        RouteVO routeVO = this.systemMenuService.listRoutes();
        return CommonResult.success(routeVO);
    }

    @Operation(summary = "路由是否存在")
    @GetMapping("/route/exist/{routeName}")
    @PreAuthorize("@ss.hasPerm('system:menu:query')")
    @ApiLog(operateType = OperateTypeEnum.SELECT, applicationName = DDServerConstant.DD_SERVER_SYSTEM, responseEnable = true, enable = false)
    public CommonResult<Boolean> existRoute(@PathVariable String routeName) {
        Boolean result = this.systemMenuService.existRoute(routeName);
        return CommonResult.success(result);
    }

    @Operation(summary = "静态路由列表")
    @GetMapping("/routes/constant")
    public CommonResult<JSONArray> listConstantRoutes() {
        ClassPathResource resource;
        String content;
        try {
            resource = new ClassPathResource("constant-route.json");
            content = resource.readUtf8Str();
        } catch (Exception e) {
            return CommonResult.success(null);
        }
        return CommonResult.success(JSONUtil.parseArray(content));
    }

    @Operation(summary = "获取菜单树")
    @GetMapping("/tree")
    @PreAuthorize("@ss.hasPerm('system:menu:query')")
    @ApiLog(operateType = OperateTypeEnum.SELECT, applicationName = DDServerConstant.DD_SERVER_SYSTEM)
    public PageResult<MenuTreeVO> menuTree(MenuPageQuery menuPageQuery) {
        List<MenuTreeVO> result = systemMenuService.menuTree(menuPageQuery);
        return PageResult.success(result);
    }

    @Operation(summary = "获取简易菜单树-供下拉列表使用")
    @GetMapping("/simple/tree")
    @PreAuthorize("@ss.hasPerm('system:menu:query')")
    public CommonResult<List<Tree<Long>>> simpleMenuTree() {
        List<Tree<Long>> result = this.systemMenuService.simpleMenuTree();
        return CommonResult.success(result);
    }

    @Operation(summary = "获取所有路由页面")
    @GetMapping("/pages/all")
    @PreAuthorize("@ss.hasPerm('system:menu:query')")
    @ApiLog(operateType = OperateTypeEnum.SELECT, applicationName = DDServerConstant.DD_SERVER_SYSTEM)
    public CommonResult<List<String>> menuPagesAll() {
        List<String> result = this.systemMenuService.menuPagesAll();
        return CommonResult.success(result);
    }

    @Operation(summary = "新增菜单")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('system:menu:create')")
    @PreventDuplicateResubmit
    @ApiLog(operateType = OperateTypeEnum.CREATE, applicationName = DDServerConstant.DD_SERVER_SYSTEM, responseEnable = true)
    public CommonResult<Long> createMenu(@Valid @RequestBody MenuForm menuForm) {
        Long menuId = this.systemMenuService.createMenu(menuForm);
        return CommonResult.success(menuId);
    }

    @Operation(summary = "修改菜单")
    @PutMapping(value = "/{id}")
    @PreAuthorize("@ss.hasPerm('system:menu:update')")
    @ApiLog(operateType = OperateTypeEnum.UPDATE, applicationName = DDServerConstant.DD_SERVER_SYSTEM, responseEnable = true)
    public CommonResult<Boolean> updateMenu(
            @NotNull(message = "不能为空") @PathVariable Long id,
            @Valid @RequestBody MenuForm menuForm
    ) {
        systemMenuService.updateMenu(id, menuForm);
        return CommonResult.success(true);
    }

    @Operation(summary = "删除菜单")
    @DeleteMapping("/{id}")
    @PreAuthorize("@ss.hasPerm('system:menu:delete')")
    @ApiLog(operateType = OperateTypeEnum.DELETE, applicationName = DDServerConstant.DD_SERVER_SYSTEM, responseEnable = true)
    public CommonResult<Boolean> deleteMenu(
            @Parameter(description = "菜单ID") @NotNull(message = "不能为空") @PathVariable("id") Long id
    ) {
        systemMenuService.deleteMenu(id);
        return CommonResult.success(true);
    }
}
